#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
Description: 维修方案强度分析模块
'''

from .base import BaseModule
from typing import Dict, Any
import gui.controls.envs as envs
from ..pops import Pops

import os
from ..uis import DlgImportRepairSchemeStrengthModel
from ..params_model import DlgBaseInfo,DlgLifeAnalysisDFR
from ..project import project_manager
from ..actions import Actions


class RepairSchemeStrengthModule(BaseModule):
    """维修方案强度分析模块"""
    def __init__(self):
        super().__init__()

        current_file = os.path.abspath(__file__)
        # 从 plugins/DUT_tiankuo/ipimas/toolbar.py 向上获取到主程序根目录
        self.main_path = os.path.normpath(os.path.join(current_file, "../../../../.."))
        # 获取 desktop 路径
        path = self.main_path.replace('\\', '/')
        self.desktop_path =f"{path}/desktop"
    
    def init_category(self, ribbon: envs.Ribbonbar) ->  Any:
        """初始化工具栏项
        Args:
            ribbon: 工具栏
        Returns:
            Any: 工具栏项
        """
        categoryRepairSchemeStrengthAnalysis =ribbon.add_category("维修方案强度分析模块") 
        pannelRepairSchemeStrengthAnalysis = ribbon.add_panel("工作流", categoryRepairSchemeStrengthAnalysis, titleHide=True)
        ribbon.add_large_btn(pannelRepairSchemeStrengthAnalysis, {
            "title": "导入模型",
            "style":"large",
            "styleSheet": "margin-right:10px; padding: 10px 20px;",
            "action": lambda *args :self.import_model()
        })
        ribbon.add_large_btn(pannelRepairSchemeStrengthAnalysis, { # 分析设置-弹出desk-pre（当前）
            "title": "分析设置",
            "style":"large",
            "styleSheet": "margin-right:10px; padding: 10px 20px;",
            "action": lambda *args :self.analysis()
        })
        ribbon.add_large_btn(pannelRepairSchemeStrengthAnalysis, {
            "title": "显示结果",
            "style":"large",
            "styleSheet": "margin-right:10px; padding: 10px 20px;",
            "action": lambda *args :envs.apis.pexecute("desktop-post.exe", shell=True, cwd=self.desktop_path)
        })
        return categoryRepairSchemeStrengthAnalysis
    
    def init_dock(self, tree) -> None:
        data = [
            {
                "title": "维修方案强度分析模块",
                "children": [
                    {
                        "title": "导入模型",
                        "events": {
                            "dbClick": lambda params: self.import_model()
                        }
                    },
                    {
                        "title": "分析设置",
                        "events": {
                            "dbClick": lambda params: self.analysis()
                        }
                    },
                    {
                        "title": "显示结果",
                        "events": {
                            "dbClick": lambda params: envs.apis.pexecute("desktop-post.exe", shell=True, cwd=self.desktop_path)
                        }
                    }
                ]
            }
        ]
        tree._set_data(data)

    def import_model(self):
        """导入模型"""
        py3d= envs.GL.get_value("py3d")
        dlg = DlgImportRepairSchemeStrengthModel(parent = py3d)
        data = project_manager.get_repair_scheme_strength_data() or {}
        dlg.setWindowTitle("导入分析模型")
        if dlg:
            dlg.init(data)
            dlg.sigOnSave.connect(lambda data: self.save_model_data(data))
            # dlg.sigOnRunParamsModeling.connect(lambda data: Pops.run_repair_scheme_strength(data))
    def save_model_data(self, data:dict={}):
        """保存模型数据"""
        project_manager.update_repair_scheme_strength_data(data)
        project_manager.save_repair_scheme_strength_data()
        # 确认后要弹出基本信息界面
        self.show_basic_info_dlg()

    def show_basic_info_dlg(self, data:dict={}, failureAreas:list=[], failureTypes:list=[]):
        """显示基本信息界面

        Args:
            data (dict, optional): 分析模型数据. Defaults to {}.
            failureAreas (list, optional): 失效区域. Defaults to [].
            failureTypes (list, optional): 失效类型. Defaults to [].
        """
        py3d= envs.GL.get_value("py3d")
        dlgBaseInfo = DlgBaseInfo.show(py3d)
        failureAreas = Actions.get_cae_failure_areas()
        data = project_manager.get_repair_scheme_strength_data() or {}
        failureTypes = [
            {
                "title": "静力分析",
                "value": "静力分析"
            },
            {
                "title": "线性屈曲分析",
                "value": "线性屈曲分析"
            },
            {
                "title": "后屈曲分析",
                "value": "后屈曲分析"
            },
            {
                "title": "DFR分析",
                "value": "DFR分析"
            }
        ]
        if dlgBaseInfo:
            curData = {
                "analysisArea": data.get("analysisArea"),   
                "failureTypes": data.get("analysisType")
            }
            dlgBaseInfo.baseInfo_save_signal.connect(lambda data: self.save_basic_info_data(data))
            dlgBaseInfo.init(data=curData, analysisAreaOpt=failureAreas, failureTypesOpt=failureTypes, select2Title="分析类型")
    def save_basic_info_data(self, data:dict={}):
        """保存基本信息数据"""
        if "failureTypes" in data:
            data["analysisType"] = data["failureTypes"]
            del data["failureTypes"]
        project_manager.update_repair_scheme_strength_data(data)
        project_manager.save_repair_scheme_strength_data()
    
    def analysis(self):
        """分析"""
        data = project_manager.get_repair_scheme_strength_data() or {}
        if data.get("analysisType") and data.get("analysisType") == "DFR分析": # dfr 分析弹出dfr分析界面
            py3d= envs.GL.get_value("py3d")
            dlgLifeAnalysisDFR = DlgLifeAnalysisDFR.show(py3d)
            if dlgLifeAnalysisDFR:
                dlgLifeAnalysisDFR.lifeAnalysisDFR_save_signal.connect(lambda data: Pops.dlgLifeAnalysisDFR_save_signal(data))
        else:
            envs.apis.pexecute("desktop-pre.exe", shell=True, cwd=self.desktop_path)

    def dlgLifeAnalysisDFR_save_signal(data:dict={}) -> None:
        """保存疲劳分析数据"""
        path = "data/ipimas"
        if not os.path.exists(path):
            os.makedirs(path)
        file = f"{path}/input_dfr.json"
        Actions.save_data(data, file, update=False)